package com.shop.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.shop.Constants;
import com.shop.MainFragment;
import com.shop.R;
import com.shop.model.Product;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**MainFragment的recycle view的adapter
 * Created by Administrator on 2016/8/8.
 */
public class MainFragmentAdapter extends  RecyclerView.Adapter<MainFragmentAdapter.MFViewHolder> {

    private LayoutInflater mInflater;
    private Context mContext;
    List<Product> list;

    public MainFragmentAdapter(Context context,List<Product> list){
        this.mContext=context;
        this.list=list;
        mInflater=LayoutInflater.from(context);

    }



    @Override
    public MFViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=mInflater.inflate(R.layout.product_item,parent,false);
        MFViewHolder viewHolder=new MFViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MFViewHolder holder, int position) {
        Product product = list.get(position);
        holder.bindProduct(product);

    }

    @Override
    public int getItemCount() {
        return list.size();
    }



    //recycle view的adapter中使用的类，此类专用于处理与每行的view相关的动作
    //一个view holder保存一种layout的view

    public class MFViewHolder extends ViewHolder{
        View mView;
        ImageView imgView;
        TextView textName;
        TextView textPrice;

        public MFViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            //一个holder对应一个view，所以最好提前把view中用到的控件都保存下来
            imgView = (ImageView) itemView.findViewById(R.id.product_img);
            textName = (TextView) itemView.findViewById(R.id.product_name);
            textPrice = (TextView) itemView.findViewById(R.id.shop_price);
        }
        @Override
        public String toString() {
            return super.toString() + " '" + textName.getText() + "'";

        }

        public void bindProduct(Product product) {
            //设置默认图像
            Picasso.with(mView.getContext())
                    .load(Constants.serverHost + product.getImage())
                    .placeholder(R.drawable.default_img)
                    .error(R.drawable.default_img)
                    .into(imgView);

            //设置头像，使用库picasso，可实现自动下载图像并进行本地缓存
            Picasso.with(mView.getContext()).load(Constants.serverHost + product.getImage()).into(imgView);
            textName.setText(product.getPname());
            textPrice.setText(String.valueOf(product.getShop_price()));

        }
    }
}
